package com.century.sjt.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.login.ChooseLanguageActivity;
import com.century.sjt.adapter.ChooseShopAdapter;
import com.century.sjt.entity.Shops;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by asus on 2016/9/2.
 */
public class TranslateOpenFragment extends BaseFragment{
    private Context mContext;
    private RequestQueue mQueue;
    private int iCurrPage = 1;
    private SwipeRefreshLayout mSwipeLayout;        //刷新组件
    private Handler mHandler;
    private Boolean isDataChangeOk = true;
    private ChooseShopAdapter adapter;
    private String userId,shopId,isTrans,transLanguage;
    private ListView mListPtRecord;
    private List<Shops> shopsList = new ArrayList<>();
    private TextView jump_small_tv;
    private LinearLayout layoutChooseLanguage;
    SharedPreferences mainSharedPreferences;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.translate_open_fragment, container, false);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        mQueue = Volley.newRequestQueue(getActivity());

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
                        TipUtil.closeProgressDialog();
                        mSwipeLayout.setRefreshing(false);
                        break;
                    case 2:
                        isDataChangeOk = true;
                        shopsList.clear();
                        iCurrPage = 1;
                        getShops();
                        break;
                    case 3:
                        if (isDataChangeOk) {
                            mSwipeLayout.setRefreshing(true);
                            iCurrPage++;
                            getShops();
                        }
                        break;

                }
            }
        };
        initView();
        initEvents();



    }
    private void initEvents() {
        SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        userId = mainSharedPreferences.getString("userId", "");
        shopId = mainSharedPreferences.getString("shopId","");
        isTrans = mainSharedPreferences.getString("isTrans","");
        transLanguage = mainSharedPreferences.getString("transLanguage","");
        if ("1".equals(isTrans)){
            layoutChooseLanguage.setEnabled(false);
        }else {
            layoutChooseLanguage.setEnabled(true);
        }
        adapter = new ChooseShopAdapter(mContext,shopsList,mHandler);
        mListPtRecord.setAdapter(adapter);

        mListPtRecord.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                // 当不滚动时
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        Message msg = new Message();
                        msg.what = 3;
                        mHandler.sendMessage(msg);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        //刷新组件
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        });
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        mListPtRecord.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                if (shopsList.get(i).isSelect()){
//                    shopsList.get(i).setSelect(false);
//                }else {
//                    shopsList.get(i).setSelect(true);
//                }
//                for (int j =0;j<shopsList.size();j++){
//                    int count = 1;
//                    if (shopsList.get(j).isSelect()){
//                        count++;
//                    }
//
//                    tvAmount.setText((count*100) + "元");
//                }
//                Message msg = new Message();
//                msg.what = 1;
//                mHandler.sendMessage(msg);
            }
        });

        layoutChooseLanguage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), ChooseLanguageActivity.class);
                intent.putExtra("type","Translate");
                startActivityForResult(intent,Constant.REQUESTCODE_LANGUAGE);
            }
        });

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==getActivity().RESULT_OK){
            switch (requestCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
                case Constant.REQUESTCODE_LANGUAGE:

                    break;
                default:
                    break;
            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }
    @Override
    public void onResume() {
        Message msg = new Message();
        msg.what = 2;
        mHandler.sendMessage(msg);
        super.onResume();
    }

    private void initView() {
        //刷新组件
        mSwipeLayout = (SwipeRefreshLayout) getView().findViewById(R.id.activity_list_refesh);
        mListPtRecord = (ListView) getView().findViewById(R.id.list_pt_record);
        jump_small_tv = (TextView) getView().findViewById(R.id.jump_small_tv);
        layoutChooseLanguage = (LinearLayout) getView().findViewById(R.id.translate_select_language);
        Typeface iconfont = Typeface.createFromAsset(getActivity().getAssets(), "iconfont.ttf");
        jump_small_tv.setTypeface(iconfont);


    }


    @Override
    public void onDestroy() {
        mQueue.cancelAll(this);
        super.onDestroy();
    }

    //获取分店

    private void getShops() {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        isDataChangeOk = false;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.getShops, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回", response, 1);
                    isDataChangeOk = true;
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject data = res.getJSONObject("data");
                    if (code.equals("407")){
                        TipUtil.showAppayRes(getActivity());
                    }
                    if (code.equals("200")) {//成功
                        JSONArray shopList = data.getJSONArray("shopList");
                        if(shopList.length()==0) {
                            isDataChangeOk = false;
                            if (iCurrPage == 1 && data.length() == 0) {
                                TipUtil.showToast(getResources().getString(R.string.error_pay_transaction_noting), mContext);
                            } else {
//                                TipUtil.showToast("无更多数据",PayTransactionActivity.this);
                            }
                        }
                        for (int i = 0 ;i<shopList.length();i++ ){
                            JSONObject shop =(JSONObject) shopList.get(i);
                            Shops shops = new Shops();
                            shops.setShopName(shop.getString("shopName"));
                            shops.setShopId(shop.getString("shopId"));
                            shops.setShopUserId(shop.getString("shopUserId"));
                            shopsList.add(shops);
                        }


                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                    }
                    TipUtil.closeProgressDialog();
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), mContext, 1);

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
                isDataChangeOk = true;
                iCurrPage--;
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("paging.currentPage",String.valueOf(iCurrPage));//当前页码
                map.put("paging.pageSize", Constant.PAGESIZE+" ");//查询条数
                map.put("merchantId",shopId);//商家
                map.put("translationService","1");// 翻译服务类型 0：未开通  1：已开通
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }


}
